package com.ctg.itrdc.imageconsole.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;


/**
 * 
 * @Description 执行http请求或command命令的工具类
 * @author <a href="mailto:18070514058@163.com">Piao.Wu</a>
 * @Data 2016年5月19日
 * @Version 1.0.0
 */
public class ExecutorUtil {
	private static final Logger logger = Logger.getLogger(ExecutorUtil.class);
	
	/**
	 * 执行http请求，返回json信息
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String executorHTTP(String url) throws Exception{
		URL localURL = new URL(url);
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
        
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        
        if (httpURLConnection.getResponseCode() >= 300) {
            throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }
        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return resultBuffer.toString();
	}
	
	
	public static boolean execShell(String cmd) {
		logger.info("The Cmd is :"+cmd);
		Runtime run = Runtime.getRuntime();
		try {
			Process p = run.exec(cmd);
			if (p != null) {
				logger.info( "执行进程号：" + p.toString());
				p.waitFor();
			} else {
				logger.error("没有pid");
				return false;
			}
		} catch (Exception e) {
			logger.error("shell 执行异常:" + cmd,e);
			return false;
		} 
		return true;
	}
	
	public static void main(String[] args) {
		
	}
	
}